#include "../include/muduo/net/TcpServer.h"
#include "../include/muduo/net/EventLoop.h"
#include "../include/muduo/net/TcpConnection.h"
#include <iostream>
#include <functional>
#include <unordered_map>

class TranslateServer
{
public:
    TranslateServer(uint16_t port) 
        : server_(&baseloop_, 
        muduo::net::InetAddress("0.0.0.0", port),
        "TranslateServer", 
        muduo::net::TcpServer::Option::kReusePort)
    {
        // server_.setConnectionCallback(TranslateServer::onConnection);   //参数不匹配(this指针)
        server_.setConnectionCallback(
            std::bind(&TranslateServer::onConnection, this, std::placeholders::_1)
        );
        server_.setMessageCallback(
            std::bind(&TranslateServer::onMessage, this, std::placeholders::_1, 
                std::placeholders::_2, std::placeholders::_3)
        );
    }

    void start() 
    {
        server_.start();    // 开始事件监听
        baseloop_.loop();   // 死循环阻塞式的事件监控
    }

private:
    // 新连接建立成功的回调函数
    void onConnection(const muduo::net::TcpConnectionPtr& conn)
    {
        if(conn->connected() == true)
            std::cout << "The new connection is successfully established!\n";
        else
            std::cout << "The new connection is closed\n";
    }

    static std::string translate(const std::string& data)
    {
        std::unordered_map<std::string, std::string> dict_map = {
            {"hello", "你好"},
            {"apple", "苹果"},
            {"eat", "吃"},
            {"happy", "快乐"}
        };
        auto it = dict_map.find(data);
        if(it == dict_map.end()) return "听不懂，退朝！\n";
        return it->second;
    }

    // 通信连接收到请求时的回调函数
    void onMessage(const muduo::net::TcpConnectionPtr& conn, muduo::net::Buffer* buffer, muduo::Timestamp)
    {
        // 1. 从buffer读数据
        std::string data = buffer->retrieveAllAsString();
        // 2. translate翻译
        std::string resp = translate(data);
        // 3. 向客户端进行响应
        conn->send(resp); 
    }
private:
    //baseloop_是epoll的事件监控，会进行描述符的事件监控，触发事件后进行io操作
    muduo::net::EventLoop baseloop_;
    //这个server对象，主要用于设置回调函数，用于告诉服务器收到什么请求该如何处理
    muduo::net::TcpServer server_;
};


int main()
{
    TranslateServer server(8888);
    server.start();
    return 0;
}